'use strict';//用户登录
// const moment = require('moment');
const utility = require("utility");
const Controller = require('egg').Controller;
class UserloginController extends Controller {
    async login() {
        const { ctx, app } = this
        const { user_name, password } = ctx.request.body
        if ( user_name && password) {
            const user = await app.mysql.query(`select user_name from users`)
            const result = user.find(item => (item.user_name === user_name));
            if (result) {
                console.log(result);
                let add = await app.mysql.query(`select password from users 
                where user_name ='${result.user_name}'`)
                if (add[0].password === utility.md5(password)) {
                    const userInfo = {
                        user_name,
                        password,
                        role: "用户",
                        login_time: Date.now() / 1000,
                        end_time: Date.now() / 1000 + 3600 * 2
                    };
                    const token = app.jwt.sign(userInfo, app.config.jwt.secret)
                    ctx.body = {
                        code: 0,
                        msg: "登录成功",
                        token
                    };
                } else {
                    ctx.body = {
                        code: 406,
                        msg: "密码错误",

                    };
                }
            } else {
                ctx.body = {
                    code: 407,
                    msg: "用户不存在",

                };
            }
        } else {
            ctx.body = {
                code: 407,
                msg: "请输入账号/密码"
            }
        }
    }





    async regist() {
        const { ctx, app } = this
        const { user_name, password, name, email, head = 'public/img/morentouxiang.webp', Telephone, time_d } = ctx.request.body
        let data;
        let mes = '';
        data = await app.mysql.query('select user_name from users');
        const result = data.find(item => item.user_name === user_name);
        console.log(result)
        if (result) {
            mes = '用户已存在';
        } else {
            const insertresult = await app.mysql.insert('users', {
                user_name,
                password: utility.md5(password),
                name,
                email,
                head,
                Telephone,
                time_d: Date.now()
            });
            if (!insertresult) {
                mes = '注册失败'

            } else {    
                mes = '注册成功'
                data = insertresult
            }
            ctx.body = {
                code:0,
                mes,
                data
            }
        }
      

    }
}

module.exports = UserloginController;




